package com.fitns.user.controller.baseConfig;

import com.alibaba.fastjson.JSON;
import com.fitns.user.conf.ZhhwResp;
import com.fitns.user.constant.Constants;
import com.fitns.user.conf.ExcelConstants;
import com.fitns.user.conf.Resp;
import com.fitns.user.dto.baseConfig.FacilityDataCondition;
import com.fitns.user.dto.baseConfig.FacilityDataDTO;
import com.fitns.user.dto.baseConfig.FacilityDataVO;
import com.fitns.user.dto.baseConfig.FaciltyTypeVo;
import com.fitns.user.model.baseConfig.TbFacilityData;
import com.fitns.user.service.baseConfig.FacilityDataService;
import com.fitns.user.service.pub.FileService;
import com.fitns.user.utils.ExcelUtils;
import com.fitns.user.utils.ResultData;
import com.fitns.user.utils.UuidUtils;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.lang.Validator;
import com.xiaoleilu.hutool.util.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Synchronized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *Created by zhou on 2018/7/25
 *
 */
@RestController
@RequestMapping("/FacilityData")
@CrossOrigin
@Api(description = "基础数据")
public class FacilityDataController  {


    @Autowired
    private FacilityDataService facilityDataService;

    @Autowired
    private FileService fileService;



    @GetMapping("/search")
    @ApiOperation("二级页面查询 ")
    public Object search( FacilityDataCondition tbFacilityData){
        PageInfo<TbFacilityData> facilityDataList= facilityDataService.search(tbFacilityData);
        facilityDataList.setPageSize(tbFacilityData.getPageSize());
        return Resp.page(facilityDataList);
    }

    @GetMapping("/findDetailed")
    @ApiOperation("查看")
    public ResultData findDetailed(FacilityDataCondition tbFacilityData){
        FacilityDataVO facilityData= facilityDataService.findDetailed(tbFacilityData);
        if(StringUtils.isEmpty(facilityData)){
            return new ResultData(300,"DEFAULT",facilityData,"");
        }
        return new ResultData(200,"SUCESS",facilityData,"");

    }

    @DeleteMapping("")
    @ApiOperation("删除")
    public ResultData delete(@RequestParam("id")Long id){
         facilityDataService.delete(id);
         return new ResultData(200,"SUCESS",null,"");
    }

    @PutMapping
    @ApiOperation("修改")
    public ResultData modify(@RequestBody TbFacilityData tbFacilityData){
        facilityDataService.modify(tbFacilityData);
        TbFacilityData facilityData=facilityDataService.modify(tbFacilityData);
        if(StringUtils.isEmpty(facilityData)){
            return new ResultData(300,"DEFAULT",facilityData,"");
        }
        return new ResultData(200,"SUCESS",facilityData,"");

    }

    @PostMapping("/insert")
    @ApiOperation("新增")
    public ResultData insert(@RequestBody FacilityDataVO tbFacilityData){
        TbFacilityData facilityData= facilityDataService.insert(tbFacilityData);
       return new ResultData(200,"SUCESS",facilityData,"");
    }

    @DeleteMapping("/deleteByType")
    @ApiOperation("")
    public ResultData deleteByType(@RequestParam("id") Long id,@RequestParam("facilityType") String facilityType){
        facilityDataService.deleteByType(id,facilityType);
        return new ResultData(200,"SUCESS",null,"");

    }

    @GetMapping("/searchFor")
    @ApiOperation("查出设施类型及数据类型下的设施数量")
    public Object searchFor(FacilityDataCondition facilityDataCondition){
        PageInfo<FaciltyTypeVo> faciltyTypeVoPageInfo=facilityDataService.searchFor(facilityDataCondition);
        faciltyTypeVoPageInfo.setPageSize(facilityDataCondition.getPageSize());
        return Resp.page(faciltyTypeVoPageInfo);
    }
    @PostMapping(value = "/importData", produces = {"text/html;charset=UTF-8"})
    @Synchronized
    //@synchronized这个结构发挥了和锁一样的作用：它避免了多个线程同时执行同一段代码。和使用NSLock进行创建锁、加锁、解锁相比，在某些情况下@synchronized会更方便、更易读。
    @ApiOperation("导入设施数据")
    public String importData(@RequestParam("file") MultipartFile file, String redisKey,@RequestParam("facilityType") String facilityType) throws Exception {
        List<List<String>> excelList=ExcelUtils.importExcel(file);
        List<String> headList=excelList.get(0);
        List<FacilityDataVO> facilityDataVOS =new ArrayList<>();
        boolean is=ExcelConstants.FACILITY_DATA_IMPORT_HEADER.XUHAO.equals(headList.get(0));
        if(ExcelConstants.FACILITY_DATA_IMPORT_HEADER.XUHAO.equals(headList.get(0))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.NAME.equals(headList.get(1))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.BEGIN_TIME.equals(headList.get(2))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.ADRESS.equals(headList.get(3))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.STATUES.equals(headList.get(4))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.AREASGE.equals(headList.get(5))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.POPULATION.equals(headList.get(6))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.COUNTER.equals(headList.get(7))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.LIABER.equals(headList.get(8))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.PHONE.equals(headList.get(9))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.TERMINAL.equals(headList.get(10))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.RFID.equals(headList.get(11))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.DESCRIPTION.equals(headList.get(12))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.LGITUDE.equals(headList.get(13))&&
                ExcelConstants.FACILITY_DATA_IMPORT_HEADER.LATITUDE.equals(headList.get(14))){
            facilityDataVOS =facilityDataService.importExcel(excelList,facilityType);
        }else {
            FacilityDataVO facilityDataVO =new FacilityDataVO();
            facilityDataVO.setMsg("模板有误，请勿修改模板！");
            facilityDataVOS.add(facilityDataVO);
        }

        ZhhwResp zhhwResp=new ZhhwResp();
        String errorData="";
        if (CollectionUtil.isNotEmpty(facilityDataVOS)) {
            errorData = JSON.toJSONString(facilityDataVOS);
        }
        if(org.apache.commons.lang3.StringUtils.isEmpty(errorData)){
            zhhwResp.setMessage("成功");
            zhhwResp.setCode(200);
        }else{
            zhhwResp.setCode(300);
            zhhwResp.setMessage("失败");
        }

        zhhwResp.setData(errorData);
        return JSON.toJSONString(zhhwResp);
    }

    @GetMapping("/exportFacilityData")
    @ApiOperation("导出设施")
    public void exportCustomer(FacilityDataCondition facilityDataCondition, HttpServletResponse response, HttpServletRequest request) throws Exception{
        List<List<String>> excelList =facilityDataService.export(facilityDataCondition);
        ExcelUtils.export(response,request,"设施列表",excelList);
    }


    /** 图片上传功能 */
    @ApiOperation("上传图片")
    @PostMapping("updateFile")
    public String inserIcon(FacilityDataVO facilityData, MultipartFile pic) throws Exception {
        // 把图片保存到图片目录下
        // 为每个文件生成一个新的文件名
        if(Validator.isNotNull(pic)) {
            String picName = UuidUtils.getUUID();
            // 取文件扩展名
            String oriName = pic.getOriginalFilename();
            if(Validator.isNull(oriName)||"".equals(oriName)){
                facilityDataService.inserImage(facilityData);
                return  JSON.toJSONString(new ResultData(200,"SUCESS",null,""));
            }
            String extName = oriName.substring(oriName.lastIndexOf("."));
            // 保存文件
            pic.transferTo(new File(Constants.IMAGE_PATH + picName + extName));

            // 把文件名保存到数据库
            facilityData.setImage(Constants.PATH+picName + extName);
            facilityDataService.inserImage(facilityData);
            return facilityData.getImage();
        }else {
            facilityDataService.inserImage(facilityData);
           return  JSON.toJSONString(new ResultData(200,"SUCESS",null,""));
        }

    }

    /**
      * IO流读取图片 by:long
      * @return
      */
    @GetMapping("/downLoadImage")
    public String IoReadImage(String imgName,HttpServletRequest request,HttpServletResponse response) throws IOException {
        return fileService.IoReadImage(imgName, request, response);
    }
}
